<template>
  <div class="food-form" :class="{ 'mobile': isMobile }">
    <n-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-placement="isMobile ? 'top' : 'left'"
      :label-width="isMobile ? 'auto' : '120px'"
    >
      <!-- 基本信息 -->
      <n-divider title-placement="left">
        <n-icon :size="16" style="margin-right: 8px;">
          <Information />
        </n-icon>
        基本信息
      </n-divider>

      <div class="form-section">
        <n-form-item label="中文名称" path="name_zh">
          <n-input
            v-model:value="formData.name_zh"
            placeholder="请输入中文名称（必填）"
            :maxlength="100"
            show-count
          />
        </n-form-item>

        <n-form-item label="英文名称" path="name_en">
          <n-input
            v-model:value="formData.name_en"
            placeholder="请输入英文名称（可选）"
            :maxlength="100"
            show-count
          />
        </n-form-item>

        <n-form-item label="其他名称">
          <n-dynamic-input
            v-model:value="formData.other_names"
            placeholder="添加其他常用名称"
            :max="5"
          />
        </n-form-item>

        <n-form-item label="其他语言">
          <div class="other-langs">
            <n-space vertical>
              <div v-for="(lang, index) in otherLangs" :key="index" class="lang-item">
                <n-input-group>
                  <n-select
                    v-model:value="lang.lang"
                    placeholder="语言"
                    :options="languageOptions"
                    style="width: 100px"
                  />
                  <n-input
                    v-model:value="lang.name"
                    placeholder="名称"
                    style="flex: 1"
                  />
                  <n-button
                    quaternary
                    type="error"
                    @click="removeLang(index)"
                    style="width: 40px"
                  >
                    <n-icon><Close /></n-icon>
                  </n-button>
                </n-input-group>
              </div>
              <n-button dashed @click="addLang" style="width: 100%">
                <n-icon><Add /></n-icon>
                添加语言
              </n-button>
            </n-space>
          </div>
        </n-form-item>
      </div>

      <!-- 基础营养素 -->
      <n-divider title-placement="left">基础营养素</n-divider>

      <n-collapse>
        <n-collapse-item title="宏量营养素" name="macros">
          <div class="nutrient-section">
            <NutrientInputDesktop
              v-model:value="formData.energy_kcal"
              v-model:rich="formData.energy_rich"
              label="能量"
              unit="kcal/100g"
              :precision="1"
              :max="900"
            />
            <NutrientInputDesktop
              v-model:value="formData.protein_g"
              v-model:rich="formData.protein_rich"
              label="蛋白质"
              unit="g/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.fat_g"
              v-model:rich="formData.fat_rich"
              label="脂肪"
              unit="g/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.omega3_g"
              v-model:rich="formData.omega3_rich"
              label="Omega-3"
              unit="g/100g"
              :precision="2"
              :max="50"
            />
            <NutrientInputDesktop
              v-model:value="formData.carb_g"
              v-model:rich="formData.carb_rich"
              label="碳水化合物"
              unit="g/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.sugars_g"
              v-model:rich="formData.sugars_rich"
              label="糖"
              unit="g/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.resistant_starch_g"
              v-model:rich="formData.resistant_starch_rich"
              label="抗性淀粉"
              unit="g/100g"
              :precision="1"
              :max="50"
            />
            <NutrientInputDesktop
              v-model:value="formData.fiber_g"
              v-model:rich="formData.fiber_rich"
              label="膳食纤维"
              unit="g/100g"
              :precision="1"
              :max="100"
            />
          </div>
        </n-collapse-item>

        <n-collapse-item title="矿物质" name="minerals">
          <div class="nutrient-section">
            <NutrientInputDesktop
              v-model:value="formData.sodium_mg"
              v-model:rich="formData.sodium_rich"
              label="钠"
              unit="mg/100g"
              :precision="1"
              :max="5000"
            />
            <NutrientInputDesktop
              v-model:value="formData.magnesium_mg"
              v-model:rich="formData.magnesium_rich"
              label="镁"
              unit="mg/100g"
              :precision="1"
              :max="1000"
            />
            <NutrientInputDesktop
              v-model:value="formData.calcium_mg"
              v-model:rich="formData.calcium_rich"
              label="钙"
              unit="mg/100g"
              :precision="1"
              :max="2000"
            />
            <NutrientInputDesktop
              v-model:value="formData.iron_mg"
              v-model:rich="formData.iron_rich"
              label="铁"
              unit="mg/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.zinc_mg"
              v-model:rich="formData.zinc_rich"
              label="锌"
              unit="mg/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.selenium_mcg"
              v-model:rich="formData.selenium_rich"
              label="硒"
              unit="mcg/100g"
              :precision="1"
              :max="1000"
            />
          </div>
        </n-collapse-item>

        <n-collapse-item title="维生素" name="vitamins">
          <div class="nutrient-section">
            <NutrientInputDesktop
              v-model:value="formData.vitamin_a_ug"
              v-model:rich="formData.vitamin_a_rich"
              label="维生素A"
              unit="μg/100g"
              :precision="1"
              :max="10000"
            />
            <NutrientInputDesktop
              v-model:value="formData.vitamin_c_mg"
              v-model:rich="formData.vitamin_c_rich"
              label="维生素C"
              unit="mg/100g"
              :precision="1"
              :max="1000"
            />
            <NutrientInputDesktop
              v-model:value="formData.vitamin_d_mcg"
              v-model:rich="formData.vitamin_d_rich"
              label="维生素D"
              unit="mcg/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.vitamin_e_mg"
              v-model:rich="formData.vitamin_e_rich"
              label="维生素E"
              unit="mg/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.thiamin_mg"
              v-model:rich="formData.thiamin_rich"
              label="维生素B1"
              unit="mg/100g"
              :precision="2"
              :max="10"
            />
            <NutrientInputDesktop
              v-model:value="formData.riboflavin_mg"
              v-model:rich="formData.riboflavin_rich"
              label="维生素B2"
              unit="mg/100g"
              :precision="2"
              :max="10"
            />
            <NutrientInputDesktop
              v-model:value="formData.vitamin_b6_mg"
              v-model:rich="formData.vitamin_b6_rich"
              label="维生素B6"
              unit="mg/100g"
              :precision="2"
              :max="10"
            />
            <NutrientInputDesktop
              v-model:value="formData.vitamin_b12_mcg"
              v-model:rich="formData.vitamin_b12_rich"
              label="维生素B12"
              unit="mcg/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.niacin_mg"
              v-model:rich="formData.niacin_rich"
              label="烟酸"
              unit="mg/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.folate_mcg"
              v-model:rich="formData.folate_rich"
              label="叶酸"
              unit="mcg/100g"
              :precision="1"
              :max="1000"
            />
          </div>
        </n-collapse-item>

        <n-collapse-item title="其他营养素" name="others">
          <div class="nutrient-section">
            <!-- 新增营养素 -->
            <NutrientInputDesktop
              v-model:value="formData.cholesterol_mg"
              v-model:rich="formData.cholesterol_rich"
              label="胆固醇"
              unit="mg/100g"
              :precision="1"
              :max="1000"
            />
            <NutrientInputDesktop
              v-model:value="formData.ash_g"
              v-model:rich="formData.ash_rich"
              label="灰分"
              unit="g/100g"
              :precision="1"
              :max="20"
            />
            <NutrientInputDesktop
              v-model:value="formData.thiamine_b1_mg"
              v-model:rich="formData.thiamine_b1_rich"
              label="硫胺素(B1)"
              unit="mg/100g"
              :precision="2"
              :max="10"
            />
            <NutrientInputDesktop
              v-model:value="formData.riboflavin_b2_g"
              v-model:rich="formData.riboflavin_b2_rich"
              label="核黄素(B2)"
              unit="g/100g"
              :precision="3"
              :max="1"
            />
            <NutrientInputDesktop
              v-model:value="formData.niacin_nicotinic_mg"
              v-model:rich="formData.niacin_nicotinic_rich"
              label="烟碱"
              unit="mg/100g"
              :precision="1"
              :max="100"
            />
            <NutrientInputDesktop
              v-model:value="formData.phosphorus_mg"
              v-model:rich="formData.phosphorus_rich"
              label="磷"
              unit="mg/100g"
              :precision="1"
              :max="2000"
            />
            <NutrientInputDesktop
              v-model:value="formData.potassium_mg"
              v-model:rich="formData.potassium_rich"
              label="钾"
              unit="mg/100g"
              :precision="1"
              :max="5000"
            />
            <NutrientInputDesktop
              v-model:value="formData.copper_mg"
              v-model:rich="formData.copper_rich"
              label="铜"
              unit="mg/100g"
              :precision="2"
              :max="10"
            />
            <NutrientInputDesktop
              v-model:value="formData.manganese_mg"
              v-model:rich="formData.manganese_rich"
              label="锰"
              unit="mg/100g"
              :precision="2"
              :max="10"
            />
            <NutrientInputDesktop
              v-model:value="formData.iodine_mg"
              v-model:rich="formData.iodine_rich"
              label="碘"
              unit="mg/100g"
              :precision="3"
              :max="1"
            />
            <NutrientInputDesktop
              v-model:value="formData.carotene_ug"
              v-model:rich="formData.carotene_rich"
              label="胡萝卜素"
              unit="μg/100g"
              :precision="1"
              :max="50000"
            />
            <NutrientInputDesktop
              v-model:value="formData.retinol_ug"
              v-model:rich="formData.retinol_rich"
              label="视黄醇"
              unit="μg/100g"
              :precision="1"
              :max="10000"
            />
            <NutrientInputDesktop
              v-model:value="formData.purine_mg"
              v-model:rich="formData.purine_rich"
              label="嘌呤"
              unit="mg/100g"
              :precision="1"
              :max="1000"
            />
          </div>

          <!-- 自定义营养素 -->
          <n-divider>自定义营养素</n-divider>
          <div class="custom-nutrients">
            <div v-for="(nutrient, index) in formData.other_nutrients" :key="index" class="custom-nutrient-item">
              <n-grid :cols="6" :x-gap="12">
                <n-grid-item>
                  <n-select
                    v-model:value="nutrient.nutrient_id"
                    placeholder="选择营养素"
                    :options="nutrientOptions"
                    @update:value="updateNutrientInfo(index, $event)"
                  />
                </n-grid-item>
                <n-grid-item>
                  <n-input-number
                    v-model:value="nutrient.amount"
                    placeholder="含量"
                    :precision="2"
                    :min="0"
                    style="width: 100%"
                  />
                </n-grid-item>
                <n-grid-item>
                  <n-input
                    v-model:value="nutrient.unit"
                    placeholder="单位"
                  />
                </n-grid-item>
                <n-grid-item>
                  <n-switch
                    v-model:value="nutrient.rich"
                  />
                  <span style="margin-left: 8px; font-size: 12px;">富含</span>
                </n-grid-item>
                <n-grid-item>
                  <n-button
                    quaternary
                    type="error"
                    @click="removeOtherNutrient(index)"
                  >
                    <n-icon><Trash /></n-icon>
                  </n-button>
                </n-grid-item>
              </n-grid>
            </div>

            <n-button dashed @click="addOtherNutrient" style="width: 100%; margin-top: 12px;">
              <n-icon><Add /></n-icon>
              添加营养素
            </n-button>
          </div>
        </n-collapse-item>
      </n-collapse>


    </n-form>

    <div class="form-actions">
      <n-button @click="handleCancel">取消</n-button>
      <n-button type="primary" @click="handleSubmit" :loading="loading">
        {{ isEditing ? '更新' : '创建' }}
      </n-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { Add, Trash } from '@vicons/ionicons5'
import type { FormInst, FormRules } from 'naive-ui'
import type { Food, Nutrient, CreateFoodForm } from '@/types'
import NutrientInputDesktop from './NutrientInputDesktop.vue'

interface Props {
  food?: Food | null
  nutrients?: Nutrient[]
}

interface Emits {
  (e: 'submit', data: CreateFoodForm): void
  (e: 'cancel'): void
}

const props = withDefaults(defineProps<Props>(), {
  food: null,
  nutrients: () => []
})

const emit = defineEmits<Emits>()

// 响应式数据
const formRef = ref<FormInst | null>(null)
const loading = ref(false)

const formData = reactive<CreateFoodForm>({
  name_zh: '',
  name_en: '',
  other_names: [],
  other_langs: {},
  // 宏量营养素
  energy_kcal: undefined,
  energy_rich: false,
  protein_g: undefined,
  protein_rich: false,
  fat_g: undefined,
  fat_rich: false,
  omega3_g: undefined,
  omega3_rich: false,
  carb_g: undefined,
  carb_rich: false,
  sugars_g: undefined,
  sugars_rich: false,
  resistant_starch_g: undefined,
  resistant_starch_rich: false,
  fiber_g: undefined,
  fiber_rich: false,
  // 矿物质
  sodium_mg: undefined,
  sodium_rich: false,
  magnesium_mg: undefined,
  magnesium_rich: false,
  calcium_mg: undefined,
  calcium_rich: false,
  iron_mg: undefined,
  iron_rich: false,
  zinc_mg: undefined,
  zinc_rich: false,
  selenium_mcg: undefined,
  selenium_rich: false,
  // 维生素
  vitamin_a_ug: undefined,
  vitamin_a_rich: false,
  vitamin_c_mg: undefined,
  vitamin_c_rich: false,
  vitamin_d_mcg: undefined,
  vitamin_d_rich: false,
  vitamin_e_mg: undefined,
  vitamin_e_rich: false,
  thiamin_mg: undefined,
  thiamin_rich: false,
  riboflavin_mg: undefined,
  riboflavin_rich: false,
  vitamin_b6_mg: undefined,
  vitamin_b6_rich: false,
  vitamin_b12_mcg: undefined,
  vitamin_b12_rich: false,
  niacin_mg: undefined,
  niacin_rich: false,
  folate_mcg: undefined,
  folate_rich: false,
  // 新增营养素
  cholesterol_mg: undefined,
  cholesterol_rich: false,
  ash_g: undefined,
  ash_rich: false,
  thiamine_b1_mg: undefined,
  thiamine_b1_rich: false,
  riboflavin_b2_g: undefined,
  riboflavin_b2_rich: false,
  niacin_nicotinic_mg: undefined,
  niacin_nicotinic_rich: false,
  phosphorus_mg: undefined,
  phosphorus_rich: false,
  potassium_mg: undefined,
  potassium_rich: false,
  copper_mg: undefined,
  copper_rich: false,
  manganese_mg: undefined,
  manganese_rich: false,
  iodine_mg: undefined,
  iodine_rich: false,
  carotene_ug: undefined,
  carotene_rich: false,
  retinol_ug: undefined,
  retinol_rich: false,
  purine_mg: undefined,
  purine_rich: false,
  other_nutrients: []
})

// 添加缺失的响应式数据
const isMobile = ref(false)
const otherLangs = ref<Array<{ lang: string; name: string }>>([])

// 语言选项
const languageOptions = [
  { label: '英语', value: 'en' },
  { label: '日语', value: 'ja' },
  { label: '韩语', value: 'ko' },
  { label: '法语', value: 'fr' },
  { label: '德语', value: 'de' },
  { label: '西班牙语', value: 'es' }
]

// 添加语言
const addLang = () => {
  otherLangs.value.push({ lang: '', name: '' })
}

// 移除语言
const removeLang = (index: number) => {
  otherLangs.value.splice(index, 1)
}

const formRules: FormRules = {
  name_zh: [
    { required: true, message: '请输入中文名称', trigger: 'blur' }
  ]
}

// 方法
const resetForm = () => {
  Object.assign(formData, {
    name_zh: '',
    name_en: '',
    other_names: [],
    other_langs: {},
    // 宏量营养素
    energy_kcal: undefined,
    energy_rich: false,
    protein_g: undefined,
    protein_rich: false,
    fat_g: undefined,
    fat_rich: false,
    omega3_g: undefined,
    omega3_rich: false,
    carb_g: undefined,
    carb_rich: false,
    sugars_g: undefined,
    sugars_rich: false,
    resistant_starch_g: undefined,
    resistant_starch_rich: false,
    fiber_g: undefined,
    fiber_rich: false,
    // 矿物质
    sodium_mg: undefined,
    sodium_rich: false,
    magnesium_mg: undefined,
    magnesium_rich: false,
    calcium_mg: undefined,
    calcium_rich: false,
    iron_mg: undefined,
    iron_rich: false,
    zinc_mg: undefined,
    zinc_rich: false,
    selenium_mcg: undefined,
    selenium_rich: false,
    // 维生素
    vitamin_a_ug: undefined,
    vitamin_a_rich: false,
    vitamin_c_mg: undefined,
    vitamin_c_rich: false,
    vitamin_d_mcg: undefined,
    vitamin_d_rich: false,
    vitamin_e_mg: undefined,
    vitamin_e_rich: false,
    thiamin_mg: undefined,
    thiamin_rich: false,
    riboflavin_mg: undefined,
    riboflavin_rich: false,
    vitamin_b6_mg: undefined,
    vitamin_b6_rich: false,
    vitamin_b12_mcg: undefined,
    vitamin_b12_rich: false,
    niacin_mg: undefined,
    niacin_rich: false,
    folate_mcg: undefined,
    folate_rich: false,
    // 新增营养素
    cholesterol_mg: undefined,
    cholesterol_rich: false,
    ash_g: undefined,
    ash_rich: false,
    thiamine_b1_mg: undefined,
    thiamine_b1_rich: false,
    riboflavin_b2_g: undefined,
    riboflavin_b2_rich: false,
    niacin_nicotinic_mg: undefined,
    niacin_nicotinic_rich: false,
    phosphorus_mg: undefined,
    phosphorus_rich: false,
    potassium_mg: undefined,
    potassium_rich: false,
    copper_mg: undefined,
    copper_rich: false,
    manganese_mg: undefined,
    manganese_rich: false,
    iodine_mg: undefined,
    iodine_rich: false,
    carotene_ug: undefined,
    carotene_rich: false,
    retinol_ug: undefined,
    retinol_rich: false,
    purine_mg: undefined,
    purine_rich: false,
    other_nutrients: []
  })
}

// 计算属性
const isEditing = computed(() => !!props.food)

// 监听props变化
watch(() => props.food, (newFood) => {
  if (newFood) {
    // 编辑模式，填充表单数据
    Object.assign(formData, {
      name_zh: newFood.name_zh,
      name_en: newFood.name_en,
      energy_kcal: newFood.energy_kcal,
      energy_rich: newFood.energy_rich,
      protein_g: newFood.protein_g,
      protein_rich: newFood.protein_rich,
      fat_g: newFood.fat_g,
      fat_rich: newFood.fat_rich,
      omega3_g: newFood.omega3_g,
      omega3_rich: newFood.omega3_rich,
      carb_g: newFood.carb_g,
      carb_rich: newFood.carb_rich,
      fiber_g: newFood.fiber_g,
      fiber_rich: newFood.fiber_rich,
      vitamin_c_mg: newFood.vitamin_c_mg,
      vitamin_c_rich: newFood.vitamin_c_rich,
      vitamin_a_ug: newFood.vitamin_a_ug,
      vitamin_a_rich: newFood.vitamin_a_rich,
      vitamin_e_mg: newFood.vitamin_e_mg,
      vitamin_e_rich: newFood.vitamin_e_rich,
      calcium_mg: newFood.calcium_mg,
      calcium_rich: newFood.calcium_rich,
      iron_mg: newFood.iron_mg,
      iron_rich: newFood.iron_rich,
      zinc_mg: newFood.zinc_mg,
      zinc_rich: newFood.zinc_rich
    })
  } else {
    // 重置表单
    resetForm()
  }
}, { immediate: true })

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    emit('submit', { ...formData })
  } catch (error) {
    console.error('Form validation failed:', error)
  } finally {
    loading.value = false
  }
}

// 计算属性
const nutrientOptions = computed(() => {
  return props.nutrients.map(n => ({
    label: n.nutrient_name_zh,
    value: n.id
  }))
})

// 自定义营养素方法
const addOtherNutrient = () => {
  if (!formData.other_nutrients) {
    formData.other_nutrients = []
  }
  formData.other_nutrients.push({
    nutrient_id: undefined,
    name_zh: '',
    amount: undefined,
    unit: '',
    rich: false
  })
}

const removeOtherNutrient = (index: number) => {
  if (formData.other_nutrients) {
    formData.other_nutrients.splice(index, 1)
  }
}

const updateNutrientInfo = (index: number, nutrientId: number) => {
  if (!formData.other_nutrients || !formData.other_nutrients[index]) return

  const nutrient = props.nutrients.find(n => n.id === nutrientId)
  if (nutrient) {
    formData.other_nutrients[index].nutrient_id = nutrientId
    formData.other_nutrients[index].name_zh = nutrient.nutrient_name_zh
    formData.other_nutrients[index].unit = nutrient.unit_zh
  }
}

const handleCancel = () => {
  emit('cancel')
}
</script>

<style scoped>
.food-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

.n-divider {
  margin: 24px 0 16px 0;
}

.n-divider:first-child {
  margin-top: 0;
}

.nutrient-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.custom-nutrients {
  margin-top: 16px;
}

.custom-nutrient-item {
  margin-bottom: 12px;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background: #fafafa;
}
</style>
